package com.weipu.common.okhttp;

import java.lang.reflect.Type;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.google.gson.Gson;
import com.weipu.common.util.JsonFormat;
import com.weipu.common.util.Logger;

public class JsonUtils {
	
	private static final String TAG="JsonUtils";

	/**
	 * Bean->JsonObject
	 * @param object
	 * @return
	 */
	public static JSONObject getJsonObjectByBean(Object object) {
		Gson gson = new Gson();
		String jsonString = gson.toJson(object);
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(jsonString);
		} catch (JSONException e) {
			Logger.i(TAG, "getJsonObjectByBean JSONException");
		}
		return jsonObject;
	}
	
	/**
	 * 将Bean转换成Json字符串
	 * @param object
	 * @return
	 */
	public static String getJsonStringByBean(Object object){
		Gson gson = new Gson();
		String jsonString = gson.toJson(object);
		Log.i("JsonUtils", JsonFormat.format(jsonString));
		return jsonString;
	}
	
	/** 
     * json字符串转成对象 
     * @param str  json字符串 
     * @param type 目标类.class
     * Person newPerson = JsonUtil.fromJson(jsonStr, Person.class);  
     * @return  
     */  
    public static <T> T fromJson(String str, Type type) {  
        Gson gson = new Gson();  
        return gson.fromJson(str, type);  
    }  
  
    /** 
     * json字符串转成对象 
     * @param str   Json字符串
     * @param type  转换对象的类型 
     *  List<Person> rtn = JsonUtil.fromJson(jsonStr, new TypeToken<List<Person>>(){}.getType()); 
     * @return  
     */  
    public static <T> T fromJson(String str, Class<T> type) {  
        Gson gson = new Gson();  
        return gson.fromJson(str, type);  
    }  

}
